﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Net;

namespace SocanClick
{
    public partial class frmMain : Form
    {
        private readonly string taskPath = Directory.GetCurrentDirectory() + "\\task.txt";

        Work work
        {
            get
            {
                Work work = new Work();

                foreach (object obj in lstTask.Items)
                {
                    string task = obj.ToString();
                    TaskItems.TaskItem ti = TaskFactory.Tasks.CreateTaskItem(task);
                    if (ti == null)
                    {
                        MessageBox.Show("“" + task + "”不是正确的任务。");
                        return null;
                    }
                    work.AddTask(ti);
                }

                int count = (int)txtNumber.Value;
                if (count <= 0)
                {
                    MessageBox.Show("循环次数必须大于0。");
                    return null;
                }
                work.LoopCount = count;

                return work;
            }
            set
            {
                lstTask.Items.Clear();
                foreach (TaskItems.TaskItem item in value.tasks)
                {
                    if (item != null)
                        lstTask.Items.Add(item.ToString());
                }
            }
        }

        frmAbout about;
        public frmMain()
        {
            InitializeComponent();
            about = new frmAbout();
            this.Text = string.Format("{0} {1}", about.AssemblyTitle, about.AssemblyVersion);
        }

        #region ******** 创建任务列表 *********
        private void btnConnect_Click(object sender, EventArgs e)
        {
            TaskItems.TaskItem ti = new TaskItems.Connect();
            lstTask.Items.Add(ti.ToString());
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            TaskItems.TaskItem ti = new TaskItems.Disconnect();
            lstTask.Items.Add(ti.ToString());
        }

        private void btnClick_Click(object sender, EventArgs e)
        {
            TaskItems.TaskItem ti = new TaskItems.Click((int)txtX.Value, (int)txtY.Value);
            lstTask.Items.Add(ti.ToString());
        }

        private void btnRightClick_Click(object sender, EventArgs e)
        {
            TaskItems.TaskItem ti = new TaskItems.RightClick((int)txtX.Value, (int)txtY.Value);
            lstTask.Items.Add(ti.ToString());
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            TaskItems.TaskItem ti = new TaskItems.OpenUrl(txtURL.Text.Trim());
            lstTask.Items.Add(ti.ToString());
        }

        private void btnSleep_Click(object sender, EventArgs e)
        {
            TaskItems.TaskItem ti = new TaskItems.Sleep((int)txtSleep.Value);
            lstTask.Items.Add(ti.ToString());
        }

        #endregion

        #region ********** 任务列表 *************
        private void btnTaskTop_Click(object sender, EventArgs e)
        {
            if (lstTask.SelectedItem != null && lstTask.SelectedIndex != 0)
            {
                object obj = lstTask.SelectedItem;
                lstTask.Items.RemoveAt(lstTask.SelectedIndex);
                lstTask.Items.Insert(0, obj);
                lstTask.SelectedIndex = 0;
            }
        }

        private void btnTaskUp_Click(object sender, EventArgs e)
        {
            if (lstTask.SelectedItem != null && lstTask.SelectedIndex > 0)
            {
                object obj = lstTask.SelectedItem;
                int i = lstTask.SelectedIndex;
                lstTask.Items.RemoveAt(i);
                lstTask.Items.Insert(i - 1, obj);
                lstTask.SelectedIndex = i - 1;
            }
        }

        private void btnTaskDown_Click(object sender, EventArgs e)
        {
            if (lstTask.SelectedItem != null && lstTask.SelectedIndex < lstTask.Items.Count - 1)
            {
                object obj = lstTask.SelectedItem;
                int i = lstTask.SelectedIndex;
                lstTask.Items.RemoveAt(i);
                lstTask.Items.Insert(i + 1, obj);
                lstTask.SelectedIndex = i + 1;
            }
        }

        private void btnTaskBottom_Click(object sender, EventArgs e)
        {
            if (lstTask.SelectedItem != null && lstTask.SelectedIndex != lstTask.Items.Count - 1)
            {
                object obj = lstTask.SelectedItem;
                lstTask.Items.RemoveAt(lstTask.SelectedIndex);
                lstTask.Items.Add(obj);
                lstTask.SelectedIndex = lstTask.Items.Count - 1;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstTask.SelectedItem != null)
            {
                int i = lstTask.SelectedIndex;
                lstTask.Items.RemoveAt(i);
                if (i - 1 >= 0)
                    lstTask.SelectedIndex = i - 1;
            }
        }

        private void btnTasksClear_Click(object sender, EventArgs e)
        {
            lstTask.Items.Clear();
        }

        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            work = DataAccess.LoadTask(taskPath);
        }

        private void picCursor_MouseDown(object sender, MouseEventArgs e)
        {
            Cursor = Cursors.SizeAll;
            timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            txtX.Value = Cursor.Position.X;
            txtY.Value = Cursor.Position.Y;
        }

        private void picCursor_MouseUp(object sender, MouseEventArgs e)
        {
            Cursor = Cursors.Default;
            timer1.Enabled = false;
        }

        private void btnClearCache_Click(object sender, EventArgs e)
        {
            lstTask.Items.Add("清空缓存");
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Work work = this.work;
            if (work == null)
                return;

            DataAccess.SaveTask(work, taskPath);

            tsslStatus.Text = "开始执行...";
            btnStart.Enabled = false;
            btnStop.Enabled = true;
            backgroundWorker1.RunWorkerAsync(work);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                btnStop.Enabled = false;
                tsslStatus.Text = "正在停止...";
                backgroundWorker1.CancelAsync();
            }
        }

        #region ********** backgroundWorker1 **********
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Work work = e.Argument as Work;

            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            for (int i = 0; i < work.LoopCount; i++)
            {
                // 上报正在执行第几次任务
                backgroundWorker1.ReportProgress(i + 1);

                foreach (TaskItems.TaskItem ti in work.tasks)
                {
                    if (backgroundWorker1.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    // 剪切板不支持多线程，单独处理一下
                    //string copy=ti.ToString();
                    //if (copy.StartsWith("复制"))
                    //{
                    //    Clipboard.SetText(copy.Replace("复制", ""));
                    //    continue;
                    //}

                    ti.Do();
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tsslStatus.Text = "就绪";
            btnStart.Enabled = true;
            btnStop.Enabled = false;

            if (e.Error != null)
                MessageBox.Show(e.Error.Message);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            tsslStatus.Text = string.Format("正在执行第{0}次...", e.ProgressPercentage);
        }
        #endregion

        private void mnuTaskSaveAs_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "文本文件 (*.txt)|*.txt";
            dlg.DefaultExt = ".txt";

            if (dlg.ShowDialog() == DialogResult.OK)
                DataAccess.SaveTask(work, dlg.FileName);
        }

        private void mnuTaskLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "文本文件 (*.txt)|*.txt";
            dlg.DefaultExt = ".txt";

            if (dlg.ShowDialog() == DialogResult.OK)
                work = DataAccess.LoadTask(dlg.FileName);
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Work work = this.work;
            if (work == null)
                return;

            DataAccess.SaveTask(work, taskPath);
        }

        private void mnuAbout_Click(object sender, EventArgs e)
        {
            about.ShowDialog();
        }
    }
}
